<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" @click="handleSubmit"> 保存信息 </el-button>
    </div>

    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :lg="24" class="card-panel-col">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>基本信息</span>
          </div>
          <el-form :model="device">
            <el-form-item label="名称" :label-width="formLabelWidth">
              <el-input v-model="device.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="位置" :label-width="formLabelWidth">
              <el-input v-model="device.position" autocomplete="off" />
            </el-form-item>
            <el-form-item label="SN" :label-width="formLabelWidth">
              <el-input v-model="device.sn" autocomplete="off" />
            </el-form-item>
            <el-form-item label="订阅" :label-width="formLabelWidth">
              <el-input v-model="device.sub" autocomplete="off" />
            </el-form-item>
            <el-form-item label="推送" :label-width="formLabelWidth">
              <el-input v-model="device.pub" autocomplete="off" />
            </el-form-item>
            <el-form-item label="型号" :label-width="formLabelWidth">
              <el-input v-model="device.model" autocomplete="off" />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <div v-for="(item, index) in axis" :key="index">
        <el-col :xs="12" :sm="12" :lg="12" class="card-panel-col">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>轴 {{ index }}</span>
              <el-button type="danger" style="float:right;" @click="handleDeleteAxis(index)"> 删除</el-button>
            </div>
            <el-form label-position="left" :label-width="formLabelWidth">
              <el-form-item label="名称">
                <el-input v-model="item.name" autocomplete="off" placeholder="请输入轴名称" style="width:300px;" />
              </el-form-item>
              <el-form-item label="运行状态">
                <el-input v-model="item.status" autocomplete="off" style="width:300px;" />
              </el-form-item>
              <el-form-item label="目标位置(mm)">
                <el-input v-model="item.target" autocomplete="off" style="width:300px;" />
              </el-form-item>
              <el-form-item label="常用位置(mm)" :label-width="formLabelWidth">
                <el-button class="button-new-tag" size="small" @click="handleAddPos(index)">+ 添加位置</el-button>
                <el-table :data="item.positions" style="width: 100%" border>
                  <el-table-column prop="name" label="位置名称" />
                  <el-table-column prop="value" label="值" />
                  <el-table-column label="操作">
                    <template slot-scope="{row, $index}">
                      <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelPos(index,$index)"> 删除 </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-form-item label="速度(r/s)">
                <el-input v-model="item.speed" autocomplete="off" style="width:300px;" />
              </el-form-item>
              <el-form-item label="螺距(um)">
                <el-input v-model="item.pitch" autocomplete="off" style="width:300px;" />
              </el-form-item>
              <el-form-item label="当前位置(um)">
                <el-input v-model="item.position" autocomplete="off" style="width:300px;" />
              </el-form-item>
              <el-form-item label="运行电流(mA)">
                <el-input v-model="item.run_current" autocomplete="off" style="width:300px;" />
              </el-form-item>
              <el-form-item label="保持电流(mA)">
                <el-input v-model="item.keep_current" autocomplete="off" style="width:300px;" />
              </el-form-item>
              <el-form-item label="编码器刻度">
                <el-input v-model="item.encoder" autocomplete="off" style="width:300px;" />
              </el-form-item>
              <el-form-item>
                <!-- <el-button class="filter-item" type="success" @click="startGet(index, item)"> 读取配置 </el-button>
                <el-button class="filter-item" type="success" @click="startSet(index, item)"> 读取配置 </el-button> -->
                <el-button class="filter-item" type="primary" @click="defaultConfig(item)"> 默认配置 </el-button>
                <el-button class="filter-item" type="success" @click="startTask(index, item, 'get')"> 读取配置 </el-button>
                <el-button class="filter-item" type="warning" @click="startTask(index, item, 'set')"> 更新配置 </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </div>
      <el-col :xs="12" :sm="12" :lg="12" class="card-panel-col">
        <el-button icon="el-icon-plus" class="plus" @click="handleAddAxis" />
      </el-col>
    </el-row>

    <el-dialog title="添加位置" :visible.sync="dialogAddPosFormVisible">
      <el-form :model="addPosform">
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="addPosform.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="值" :label-width="formLabelWidth">
          <el-input v-model="addPosform.value" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddPosFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddPosConfirm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { editDevice } from '@/api/device'
import { CMD_AXIS } from '@/utils/cmd'

export default {
  name: 'RG601',
  components: { },
  data() {
    return {
      formLabelWidth: '200px',
      device: null,
      task: {
        name: '',
        axis_number: 0,
        config: null,
        step: 0,
        timer_cnt: 0,
        flag: false,
        done: false
      },
      axis: [],
      // 添加位置相关变量
      dialogAddPosFormVisible: false,
      addPosIndex: 0,
      addPosform: {
        name: '',
        value: 0
      }
    }
  },
  created() {
    this.device = this.$route.query
    this.axis = this.device.value.axis
    console.log('设备信息')
    console.log(this.device)
    console.log(this.axis)
    if (this.axis === undefined) {
      this.axis = []
    }
    this.subscribe(this.device.pub)
    // this.task_timer = setInterval(this.taskTimer, 3000)
  },
  methods: {
    // 提交保存
    handleSubmit() {
      this.device.value.axis = this.axis
      editDevice(this.device).then(response => {
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.$router.push({ path: '/device/index' })
        } else this.$message(response.message)
      })
    },
    // 添加坐标
    handleAddAxis() {
      this.axis.push({
        name: '',
        status: 0,
        target: 0,
        positions: [],
        speed: 0,
        pitch: 0,
        position: 0,
        run_current: 0,
        keep_current: 0,
        encoder: 0
      })
    },
    handleDeleteAxis(index) {
      this.axis.splice(index, 1)
    },

    // 常用位置
    handleDelPos(axis_index, pos_index) {
      this.axis[axis_index].positions.splice(pos_index, 1)
    },

    handleAddPos(index) {
      this.addPosIndex = index
      this.dialogAddPosFormVisible = true
    },

    handleAddPosConfirm() {
      console.log(this.axis)
      this.axis[this.addPosIndex].positions.push(JSON.parse(JSON.stringify(this.addPosform)))
      this.dialogAddPosFormVisible = false
    },

    // 默认配置
    defaultConfig(item) {
      item.speed = 8
      item.pitch = 5000
      item.position = 0
      item.run_current = 20
      item.keep_current = 10
      item.encoder = 80
    },

    // 获取命令
    getCmd(axis_number, step, data) {
      var code = null
      switch (step) {
        case 0:
          code = CMD_AXIS[axis_number].get_speed
          break
        case 1:
          code = CMD_AXIS[axis_number].get_pitch
          break
        case 2:
          code = CMD_AXIS[axis_number].get_position
          break
        case 3:
          code = CMD_AXIS[axis_number].get_run_current
          break
        case 4:
          code = CMD_AXIS[axis_number].get_keep_current
          break
        case 5:
          code = CMD_AXIS[axis_number].get_encoder
          break

        default:
          break
      }
      // code: '3' + axis_number * 2 + step,
      this.publish(this.device.sub, JSON.stringify({
        code: code.toString(),
        msg: '1'
      }))
    },

    // 设置命令
    setCmd(axis_number, step, data) {
      var msg = null
      var code = null
      switch (step) {
        case 0:
          code = CMD_AXIS[axis_number].set_speed
          msg = data.speed
          break
        case 1:
          code = CMD_AXIS[axis_number].set_pitch
          msg = data.pitch
          break
        case 2:
          code = CMD_AXIS[axis_number].set_position
          msg = data.position
          break
        case 3:
          code = CMD_AXIS[axis_number].set_run_current
          msg = data.run_current
          break
        case 4:
          code = CMD_AXIS[axis_number].set_keep_current
          msg = data.keep_current
          break
        case 5:
          code = CMD_AXIS[axis_number].set_encoder
          msg = data.encoder
          break

        default:
          break
      }
      // code: '2' + axis_number * 2 + step,
      this.publish(this.device.sub, JSON.stringify({
        code: code.toString(),
        msg: msg.toString()
      }))
    },

    startTask(index, item, name) {
      console.log('执行任务')
      console.log(name)
      console.log(item)
      console.log(index)

      var task = this.task
      task.timer_cnt = 0
      task.step = 0
      task.once_done = true
      // 获取时清空参数
      if (name === 'get') {
        this.axis[index].speed = 0
        this.axis[index].pitch = 0
        this.axis[index].position = 0
        this.axis[index].run_current = 0
        this.axis[index].keep_current = 0
        this.axis[index].encoder = 0
      }

      this.timer = setInterval(() => {
        // 完成
        if (task.done) {
          this.$message({ message: '完成~', type: 'success' })
          clearInterval(this.timer)
        }
        if (task.step > 4) {
          clearInterval(this.timer)
          this.$message({ message: '完成~', type: 'success' })
        }
        // 发送命令
        if (name === 'get') {
          this.getCmd(index, task.step, item)
        }
        if (name === 'set') {
          this.setCmd(index, task.step, item)
        }
        // 完成一次
        if (task.once_done) {
          task.once_done = false
          task.timer_cnt = 0
          task.step += 1
        }
        // 超时
        task.timer_cnt += 1
        if (task.timer_cnt > 2) {
          this.$message({ message: '读取超时~', type: 'warning' })
          task.flag = false
          clearInterval(this.timer)
        }
      }, 500)
    },

    subscribe(val) {
      console.log('订阅')
      console.log('topic:' + val)
      this.$mqtt.subscribe(val)
    },
    publish(topic, message) {
      console.log('推送消息')
      console.log('topic:' + topic)
      console.log('message:' + message)
      this.$mqtt.publish(topic, message)
    },

    codeDeal(code, msg) {
      this.task.once_done = true
      for (var i = 0; i < CMD_AXIS.length; i++) {
        if (CMD_AXIS[i].get_speed === code) {
          this.axis[i].speed = msg
        }
        if (CMD_AXIS[i].get_pitch === code) {
          this.axis[i].pitch = msg
        }
        if (CMD_AXIS[i].get_position === code) {
          this.axis[i].position = msg
        }
        if (CMD_AXIS[i].get_run_current === code) {
          this.axis[i].run_current = msg
        }
        if (CMD_AXIS[i].get_keep_current === code) {
          this.axis[i].keep_current = msg
        }
        if (CMD_AXIS[i].get_encoder === code) {
          this.axis[i].encoder = msg
        }
      }
    }
  },
  mqtt: {
    '#'(data, topic) {
      console.log('收到消息')
      console.log('topic:' + topic)
      console.log('payload: ' + String.fromCharCode.apply(null, data))
      if (topic === this.device.pub) {
        var payload = JSON.parse(data)
        console.log(payload)
        console.log('主题正确')
        this.codeDeal(parseInt(payload.aswcode), payload.aswmsg)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card{
  margin-bottom: 20px;
}

.plus{
  min-width: 100%;
  min-height: 300px;
  text-align: center;
  font-size: 108px;
}

</style>
